﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using EraNet.Core;
using EraNet.Data;
using EraNet.Core.Model.Account;
using EraNet.Core.Model.SysManage;

using EraNet.Common;
using EraNet.Services.Account;
using EraNet.Services.Drivings;
using EraNet.Services.SysManage;
using EraNet.WebApp.AppCore;

namespace EraNet.WebApp.IMS
{
    public class TrainingController : IMSBasePage
    {
        #region Fields
        private readonly ISysCardsService _syscardsService;
        private readonly IMemberService _memberService;
        private readonly IDriveSchoolService _driveschoolService;
        private readonly IDictionaryService _dictionaryService;
        private readonly ISysConfigService _sysconfigService;
        #endregion

        #region Constructors
        public TrainingController(IDictionaryService dictionaryService, ISysConfigService sysconfigService, ISysCardsService syscardsService, IMemberService memberService,IDriveSchoolService driveschoolService)
        {
            this._syscardsService = syscardsService;
            this._dictionaryService = dictionaryService;
            this._sysconfigService = sysconfigService;
            this._memberService = memberService;
            this._driveschoolService = driveschoolService;
        }
        #endregion

        public ActionResult StudentList(int? page)
        {
            ViewBag.myTabId = "1";
            if (page == null) page = 1;
            page = page - 1;
            int pagesize = 20;
            #region 获取当前用户信息，根据当前用户信息取考试信息
            Employee m = _driveschoolService.GetLoginClient();
            //var list= _examinationService.GetExamLogsBySchool(m.SchoolID, (int)page, 20);
            var list = _memberService.GetMemberBySchool(null, null, m.SchoolID, pagesize, (int)page, false);

            int[] arrMemberId = new int[list.Count];

            for(int i=0;i<list.Count;i++)
            {
                arrMemberId[i]=list[i].Id;
            }


            ViewData["cardAllotList"] = _syscardsService.GetCardAllotLogs(arrMemberId); 
            #endregion
            return View(list);
        }

        [HttpGet]
        public ActionResult StudentEdit(int memberId=0)
        {
            Member m = new Member();
            if (memberId == 0)
            {
                m.Nation = "汉";
                m.Birthday = DateTime.Now;
                m.Sex = "男";
                m.Email = "无";
                m.Address = "无";
                m.LearnCar = "C1";
                Common.Utility.WriteCookie("editType", "add");
            }
            else
            {
                Common.Utility.WriteCookie("editType", "edit");
                
                m = _memberService.GetMemberById(memberId);
                Common.Utility.WriteCookie("updAccName", m.AccountName);
                Common.Utility.WriteCookie("updIdCard", m.IDCard);
            }
            return View(m);
        }
        
        [HttpPost]
        public ActionResult StudentEdit(Member m)
        {
            Employee emp=_driveschoolService.GetLoginClient();
            string editType=Common.Utility.GetCookie("editType");
            if (editType.Equals("add"))
            {
                m.Password = Utility.MD5(m.AccountName); //驾校添加用户 密码默认跟账号一样
                m.SchoolID = emp.SchoolID;
                m.LastLoginDate = DateTime.Now;
                m.ExpireDate = Convert.ToDateTime("1900-01-01");  //默认新加
                m.CreateDate = DateTime.Now;
                m.Status = 1;
                m.IsSuper = false;
                if (_memberService.InsertMember(m) > 0)
                {
                    ViewData["msg"] = "1";
                }
                else
                    ViewData["msg"] = "0";
            }
            else
            {
                Member member = _memberService.GetMemberById(m.Id);
                member.Names = m.Names;
                member.AccountName = m.AccountName;
                member.IDCard = m.IDCard;
                member.Telephone = m.Telephone;
                member.Email = m.Email;
                member.Address = m.Address;
                member.Nation = m.Nation;
                member.Sex = m.Sex;
                member.Birthday = m.Birthday;
                member.LearnCar = m.LearnCar;
                if (_memberService.UpdateMember(member) > 0)
                {
                    ViewData["msg"] = "1";
                }
                else
                    ViewData["msg"] = "0";
            }

            return View(m);
        }


        public ActionResult StudentInfo(int Id)
        {
            #region 获取无效ID时
            if (Id <= 0) return null;
            #endregion
            var m = _memberService.GetMemberById(Id);
            var mconfig = _memberService.GetMemberAdjById(Id);
            ViewBag.Mcfg = mconfig;
            return View(m);
        }

        /// <summary>
        /// 分配学习卡
        /// </summary>
        /// <param name="cardNo">学习卡号</param>
        /// <param name="cardPwd">卡密</param>
        /// <param name="memberId">学员ID</param>
        /// <param name="cardId">卡片ID</param>
        /// <returns></returns>
        public JsonResult AssigCard(string cardNo,string cardPwd,int memberId = 0, int cardId = 0 )
        {
            int result = 0;

            #region 为空校验
            //请先输入学习卡号
            if (string.IsNullOrEmpty(cardNo))
                return Json("1", JsonRequestBehavior.AllowGet); //Core.Model.Common.BaseMessage.Member_Name_IsNull;
            else { 
               //验证卡号是否存在并未分配
                if (_syscardsService.isExistsByCardNo(cardNo.Trim()))
                {
                    return Json("2", JsonRequestBehavior.AllowGet);
                }
            }
            #endregion

            CardAllotLogs cardAllLog = new CardAllotLogs();
            cardAllLog.CardId = cardId;
            cardAllLog.MemberId = memberId;
            cardAllLog.CardPwd = cardPwd;
            cardAllLog.CardNo = cardNo;
            cardAllLog.CreatedOnUtc = DateTime.Now;

            if (_syscardsService.InsertCardAllotLog(cardAllLog, cardId))
                 result = 3;

            return Json(result.ToString(), JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 获取一张未分配的学习卡
        /// </summary>
        /// <param name="cardNo"></param>
        /// <param name="cardPwd"></param>
        /// <param name="memberId"></param>
        /// <param name="cardId"></param>
        /// <returns></returns>
        public JsonResult GetSingleCardAssigNo()
        {
            int schoolId = _driveschoolService.GetLoginClient().Id;
            SysCards card = _syscardsService.GetSingleCardBySchoolId(schoolId);

            if (card != null)
            {
                string CardNo = card.Markstr + card.CardNo;
                return Json(new { CardNo, card.Id, card.CardPassword }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("1", JsonRequestBehavior.AllowGet);
            }
        }
    }
}
